package com.inspur.springcloudoauth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.inspur.springcloudoauth.dao.PortalUserMapper;
import com.inspur.springcloudoauth.entity.PortalUser;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 自定义用户处理的逻辑
 *
 * 用户的信息的service
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    /**
     * 日志处理类
     */
    private org.slf4j.Logger logger =  LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    PortalUserMapper portalUserMapper;

    /**
     * 根据用户名加载用户信息
     *
     * @param username 用户名
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("表单登录用户名:" + username);
        System.out.println("表单登录用户名:" + username);

        // 这里应该去数据库里查询

        //在这里用了Spring默认的一个类User,在自己的实现过程中并不一定要用Spring的类
        //可以自己定义一个对象实现UserDetail接口。
        List<PortalUser> list = portalUserMapper.selectList(new QueryWrapper<PortalUser>().eq("username",username));
        // 用户不存在
        if (list.size() ==0){
            return null;
        }

        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();

        grantedAuthorityList.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return "admin";
            }
        });

        String pWord =passwordEncoder.encode(list.get(0).getPassword());
        System.out.println("用户密码:" + pWord);
        logger.info("用户密码:" + pWord);

        // 加密密码，权限列表
        return new User(username, pWord,true,
                true,
                true,
                true,
                grantedAuthorityList);

        // 明文密码，权限列表
//        return new User("test","123",true,
//                true,
//                true,
//                true,
//                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
